import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
 
import store from '../store'
// 创建 axios 实例
const api = axios.create({
  baseURL: 'https://rwxcoin.com', // 替换为你的 API 基础 URL
  timeout: 30000, // 请求超时时间
});

// 请求拦截器
api.interceptors.request.use(
  (config: any) => {
    const state = store.getState();
    const token = state.user.token;  
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    if (error.message === 'NETWORK_UNAVAILABLE') {
      return Promise.reject('网络连接已断开');
    }
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    if (response.data.code === 401) {
      // 清除所有路由堆栈
      require('expo-router').router.replace('/(auth)/login');
      return {errMsg: '登录过期',code:401}
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 封装常用的请求方法
const get = <T>(url: string, params?: any): Promise<T> => api.get(url, { params });
const post = <T>(url: string, data?: any): Promise<T> => {
  let config: AxiosRequestConfig = {};
  if (data instanceof FormData) {
    config.headers = {
      'Content-Type': 'multipart/form-data'
    };
  }
  return api.post(url, data, config);
};
const put = <T>(url: string, data?: any): Promise<T> => {
  let config: AxiosRequestConfig = {};
  if (data instanceof FormData) {
    config.headers = {
      'Content-Type': 'multipart/form-data'
    };
  }
  return api.put(url, data, config);
};
const del = <T>(url: string): Promise<T> => api.delete(url);

export { get, post, put, del };
